[[...path]].page.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. import React, { ReactNode, useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import type {
  11. GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { useCurrentGrowiLayoutFluidClassName, useEditorModeClassName } from '~/client/services/layout';
  19. import { PageView } from '~/components/Page/PageView';
  20. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  21. import type { CrowiRequest } from '~/interfaces/crowi-request';
  22. import type { EditorConfig } from '~/interfaces/editor-settings';
  23. import type { IPageGrantData } from '~/interfaces/page';
  24. import type { RendererConfig } from '~/interfaces/services/renderer';
  25. import type { PageModel, PageDocument } from '~/server/models/page';
  26. import type { PageRedirectModel } from '~/server/models/page-redirect';
  27. import {
  28. useCurrentUser,
  29. useIsForbidden, useIsSharedUser,
  30. useIsEnabledStaleNotification, useIsIdenticalPath,
  31. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  32. useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  33. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  34. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPathname,
  35. useIsSlackConfigured, useRendererConfig,
  36. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useIsContainerFluid, useIsNotCreatable,
  37. } from '~/stores/context';
  38. import { useEditingMarkdown } from '~/stores/editor';
  39. import { useHasDraftOnHackmd, usePageIdOnHackmd, useRevisionIdHackmdSynced } from '~/stores/hackmd';
  40. import {
  41. useSWRxCurrentPage, useSWRxIsGrantNormalized, useCurrentPageId, useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  42. } from '~/stores/page';
  43. import { useRedirectFrom } from '~/stores/page-redirect';
  44. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  45. import { useSelectedGrant } from '~/stores/ui';
  46. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  47. import loggerFactory from '~/utils/logger';
  48. import { BasicLayout } from '../components/Layout/BasicLayout';
  49. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  50. import type { GrowiSubNavigationSwitcherProps } from '../components/Navbar/GrowiSubNavigationSwitcher';
  51. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  52. import type { NextPageWithLayout } from './_app.page';
  53. import type { CommonProps } from './utils/commons';
  54. import {
  55. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig,
  56. } from './utils/commons';
  57. declare global {
  58. // eslint-disable-next-line vars-on-top, no-var
  59. var globalEmitter: EventEmitter;
  60. }
  61. const GrowiPluginsActivator = dynamic(() => import('~/features/activate-plugin').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  62. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  63. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  64. const GrowiSubNavigationSwitcher = dynamic<GrowiSubNavigationSwitcherProps>(() => import('../components/Navbar/GrowiSubNavigationSwitcher')
  65. .then(mod => mod.GrowiSubNavigationSwitcher), { ssr: false });
  66. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  67. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  68. const TemplateModal = dynamic(() => import('../components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  69. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  70. const logger = loggerFactory('growi:pages:all');
  71. const {
  72. isPermalink: _isPermalink, isTrashPage: _isTrashPage, isCreatablePage,
  73. } = pagePathUtils;
  74. const { removeHeadingSlash } = pathUtils;
  75. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  76. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  77. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  78. {
  79. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  80. return v?.data != null
  81. && v?.data.toObject != null
  82. && v?.meta != null
  83. && isIPageInfoForEntity(v.meta);
  84. },
  85. serialize: (v) => {
  86. return {
  87. data: superjson.stringify(v.data.toObject()),
  88. meta: superjson.stringify(v.meta),
  89. };
  90. },
  91. deserialize: (v) => {
  92. return {
  93. data: superjson.parse(v.data),
  94. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  95. };
  96. },
  97. },
  98. 'IPageToShowRevisionWithMetaTransformer',
  99. );
  100. // GrowiContextualSubNavigation for NOT shared page
  101. type GrowiContextualSubNavigationProps = {
  102. isLinkSharingDisabled: boolean,
  103. }
  104. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  105. const { isLinkSharingDisabled } = props;
  106. const { data: currentPage } = useSWRxCurrentPage();
  107. return (
  108. <div data-testid="grw-contextual-sub-nav">
  109. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled}/>
  110. </div>
  111. );
  112. };
  113. const PutbackPageModal = (): JSX.Element => {
  114. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  115. return <PutbackPageModal />;
  116. };
  117. type Props = CommonProps & {
  118. pageWithMeta: IPageToShowRevisionWithMeta | null,
  119. // pageUser?: any,
  120. redirectFrom?: string;
  121. // shareLinkId?: string;
  122. isLatestRevision?: boolean,
  123. isIdenticalPathPage?: boolean,
  124. isForbidden: boolean,
  125. isNotFound: boolean,
  126. isNotCreatable: boolean,
  127. // isAbleToDeleteCompletely: boolean,
  128. templateTagData?: string[],
  129. templateBodyData?: string,
  130. isSearchServiceConfigured: boolean,
  131. isSearchServiceReachable: boolean,
  132. isSearchScopeChildrenAsDefault: boolean,
  133. isSlackConfigured: boolean,
  134. // isMailerSetup: boolean,
  135. isAclEnabled: boolean,
  136. // hasSlackConfig: boolean,
  137. drawioUri: string | null,
  138. hackmdUri: string,
  139. noCdn: string,
  140. // highlightJsStyle: string,
  141. isAllReplyShown: boolean,
  142. isContainerFluid: boolean,
  143. editorConfig: EditorConfig,
  144. isEnabledStaleNotification: boolean,
  145. isEnabledAttachTitleHeader: boolean,
  146. // isEnabledLinebreaks: boolean,
  147. // isEnabledLinebreaksInComments: boolean,
  148. adminPreferredIndentSize: number,
  149. isIndentSizeForced: boolean,
  150. disableLinkSharing: boolean,
  151. grantData?: IPageGrantData,
  152. rendererConfig: RendererConfig,
  153. };
  154. const Page: NextPageWithLayout<Props> = (props: Props) => {
  155. // register global EventEmitter
  156. if (isClient() && window.globalEmitter == null) {
  157. window.globalEmitter = new EventEmitter();
  158. }
  159. const router = useRouter();
  160. useCurrentUser(props.currentUser ?? null);
  161. // commons
  162. useEditorConfig(props.editorConfig);
  163. useCsrfToken(props.csrfToken);
  164. // page
  165. useIsContainerFluid(props.isContainerFluid);
  166. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  167. useIsForbidden(props.isForbidden);
  168. useIsNotCreatable(props.isNotCreatable);
  169. useRedirectFrom(props.redirectFrom ?? null);
  170. useIsSharedUser(false); // this page cann't be routed for '/share'
  171. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  172. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  173. useIsSearchPage(false);
  174. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  175. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  176. useIsSearchServiceReachable(props.isSearchServiceReachable);
  177. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  178. useIsSlackConfigured(props.isSlackConfigured);
  179. // useIsMailerSetup(props.isMailerSetup);
  180. useIsAclEnabled(props.isAclEnabled);
  181. // useHasSlackConfig(props.hasSlackConfig);
  182. useHackmdUri(props.hackmdUri);
  183. // useNoCdn(props.noCdn);
  184. useDefaultIndentSize(props.adminPreferredIndentSize);
  185. useIsIndentSizeForced(props.isIndentSizeForced);
  186. useDisableLinkSharing(props.disableLinkSharing);
  187. useRendererConfig(props.rendererConfig);
  188. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  189. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  190. useIsAllReplyShown(props.isAllReplyShown);
  191. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  192. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  193. const { pageWithMeta } = props;
  194. const pageId = pageWithMeta?.data._id;
  195. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  196. const revisionBody = pageWithMeta?.data.revision?.body;
  197. usePageIdOnHackmd(pageWithMeta?.data.pageIdOnHackmd);
  198. useHasDraftOnHackmd(pageWithMeta?.data.hasDraftOnHackmd ?? false);
  199. useCurrentPathname(props.currentPathname);
  200. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  201. const { mutate: mutateIsNotFound } = useIsNotFound();
  202. const { mutate: mutateCurrentPageId } = useCurrentPageId();
  203. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  204. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  205. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  206. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  207. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  208. const { mutate: mutateRevisionIdHackmdSynced } = useRevisionIdHackmdSynced();
  209. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  210. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  211. useSetupGlobalSocket();
  212. useSetupGlobalSocketForPage(pageId);
  213. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName(pageWithMeta?.data);
  214. const shouldRenderPutbackPageModal = pageWithMeta != null
  215. ? _isTrashPage(pageWithMeta.data.path)
  216. : false;
  217. // sync grant data
  218. useEffect(() => {
  219. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  220. mutateSelectedGrant(grantDataToApply);
  221. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  222. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  223. useEffect(() => {
  224. const decodedURI = decodeURI(window.location.pathname);
  225. if (isClient() && decodedURI !== props.currentPathname) {
  226. const { search, hash } = window.location;
  227. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  228. }
  229. }, [props.currentPathname, router]);
  230. // initialize mutateEditingMarkdown only once per page
  231. // need to include useCurrentPathname not useCurrentPagePath
  232. useEffect(() => {
  233. if (props.currentPathname != null) {
  234. mutateEditingMarkdown(revisionBody);
  235. }
  236. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  237. useEffect(() => {
  238. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  239. mutateRevisionIdHackmdSynced(pageWithMeta?.data.revisionHackmdSynced);
  240. }, [mutateRemoteRevisionId, mutateRevisionIdHackmdSynced, pageWithMeta?.data.revision?._id, pageWithMeta?.data.revisionHackmdSynced]);
  241. useEffect(() => {
  242. mutateCurrentPageId(pageId ?? null);
  243. }, [mutateCurrentPageId, pageId]);
  244. useEffect(() => {
  245. mutateIsNotFound(props.isNotFound);
  246. }, [mutateIsNotFound, props.isNotFound]);
  247. useEffect(() => {
  248. mutateIsLatestRevision(props.isLatestRevision);
  249. }, [mutateIsLatestRevision, props.isLatestRevision]);
  250. useEffect(() => {
  251. mutateTemplateTagData(props.templateTagData);
  252. }, [props.templateTagData, mutateTemplateTagData]);
  253. useEffect(() => {
  254. mutateTemplateBodyData(props.templateBodyData);
  255. }, [props.templateBodyData, mutateTemplateBodyData]);
  256. const title = generateCustomTitleForPage(props, pagePath);
  257. return (
  258. <>
  259. <Head>
  260. <title>{title}</title>
  261. </Head>
  262. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  263. <header className="py-0 position-relative">
  264. <div id="grw-subnav-container">
  265. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  266. </div>
  267. </header>
  268. <div className="d-edit-none">
  269. <GrowiSubNavigationSwitcher isLinkSharingDisabled={props.disableLinkSharing} />
  270. </div>
  271. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  272. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  273. <DisplaySwitcher
  274. pageView={
  275. <PageView
  276. pagePath={pagePath}
  277. initialPage={pageWithMeta?.data}
  278. rendererConfig={props.rendererConfig}
  279. />
  280. }
  281. />
  282. <PageStatusAlert />
  283. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  284. </div>
  285. </>
  286. );
  287. };
  288. type LayoutProps = Props & {
  289. children?: ReactNode
  290. }
  291. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  292. const className = useEditorModeClassName();
  293. // init sidebar config with UserUISettings and sidebarConfig
  294. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  295. return (
  296. <BasicLayout className={className}>
  297. {children}
  298. </BasicLayout>
  299. );
  300. };
  301. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  302. return (
  303. <>
  304. <GrowiPluginsActivator />
  305. <DrawioViewerScript />
  306. <Layout {...page.props}>
  307. {page}
  308. </Layout>
  309. <UnsavedAlertDialog />
  310. <DescendantsPageListModal />
  311. <DrawioModal />
  312. <HandsontableModal />
  313. <TemplateModal />
  314. </>
  315. );
  316. };
  317. function getPageIdFromPathname(currentPathname: string): string | null {
  318. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  319. }
  320. class MultiplePagesHitsError extends ExtensibleCustomError {
  321. pagePath: string;
  322. constructor(pagePath: string) {
  323. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  324. this.pagePath = pagePath;
  325. }
  326. }
  327. // apply parent page grant fot creating page
  328. async function applyGrantToPage(props: Props, ancestor: any) {
  329. await ancestor.populate('grantedGroup');
  330. const grant = {
  331. grant: ancestor.grant,
  332. };
  333. const grantedGroup = ancestor.grantedGroup ? {
  334. grantedGroup: {
  335. id: ancestor.grantedGroup.id,
  336. name: ancestor.grantedGroup.name,
  337. },
  338. } : {};
  339. props.grantData = Object.assign(grant, grantedGroup);
  340. }
  341. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  342. const { model: mongooseModel } = await import('mongoose');
  343. const req: CrowiRequest = context.req as CrowiRequest;
  344. const { crowi } = req;
  345. const { revisionId } = req.query;
  346. const Page = crowi.model('Page') as PageModel;
  347. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  348. const { pageService } = crowi;
  349. let currentPathname = props.currentPathname;
  350. const pageId = getPageIdFromPathname(currentPathname);
  351. const isPermalink = _isPermalink(currentPathname);
  352. const { user } = req;
  353. if (!isPermalink) {
  354. // check redirects
  355. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  356. if (chains != null) {
  357. // overwrite currentPathname
  358. currentPathname = chains.end.toPath;
  359. props.currentPathname = currentPathname;
  360. // set redirectFrom
  361. props.redirectFrom = chains.start.fromPath;
  362. }
  363. // check whether the specified page path hits to multiple pages
  364. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  365. if (count > 1) {
  366. throw new MultiplePagesHitsError(currentPathname);
  367. }
  368. }
  369. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  370. const page = pageWithMeta?.data as unknown as PageDocument;
  371. // add user to seen users
  372. if (page != null && user != null) {
  373. await page.seen(user);
  374. }
  375. // populate & check if the revision is latest
  376. if (page != null) {
  377. page.initLatestRevisionField(revisionId);
  378. await page.populateDataToShowRevision();
  379. props.isLatestRevision = page.isLatestRevision();
  380. }
  381. if (page == null && user != null) {
  382. const templateData = await Page.findTemplate(props.currentPathname);
  383. if (templateData != null) {
  384. props.templateTagData = templateData.templateTags as string[];
  385. props.templateBodyData = templateData.templateBody as string;
  386. }
  387. // apply pagrent page grant
  388. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  389. if (ancestor != null) {
  390. await applyGrantToPage(props, ancestor);
  391. }
  392. }
  393. props.pageWithMeta = pageWithMeta;
  394. }
  395. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  396. const req: CrowiRequest = context.req as CrowiRequest;
  397. const { crowi } = req;
  398. const Page = crowi.model('Page') as PageModel;
  399. const { currentPathname } = props;
  400. const pageId = getPageIdFromPathname(currentPathname);
  401. const isPermalink = _isPermalink(currentPathname);
  402. const page = props.pageWithMeta?.data;
  403. if (props.isIdenticalPathPage) {
  404. props.isNotCreatable = true;
  405. }
  406. else if (page == null) {
  407. props.isNotFound = true;
  408. props.isNotCreatable = !isCreatablePage(currentPathname);
  409. // check the page is forbidden or just does not exist.
  410. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  411. props.isForbidden = count > 0;
  412. }
  413. else {
  414. props.isNotFound = page.isEmpty;
  415. props.isNotCreatable = false;
  416. props.isForbidden = false;
  417. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  418. if (isPermalink && page.isEmpty) {
  419. props.currentPathname = page.path;
  420. }
  421. // /path/to/page ==> /62a88db47fed8b2d94f30000
  422. if (!isPermalink && !page.isEmpty) {
  423. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  424. if (!isToppage) {
  425. props.currentPathname = `/${page._id}`;
  426. }
  427. }
  428. }
  429. }
  430. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  431. // const req: CrowiRequest = context.req as CrowiRequest;
  432. // const { crowi } = req;
  433. // const UserModel = crowi.model('User');
  434. // if (isUserPage(props.currentPagePath)) {
  435. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  436. // if (user != null) {
  437. // props.pageUser = JSON.stringify(user.toObject());
  438. // }
  439. // }
  440. // }
  441. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  442. const req: CrowiRequest = context.req as CrowiRequest;
  443. const { crowi } = req;
  444. const {
  445. searchService, configManager, aclService,
  446. } = crowi;
  447. props.isSearchServiceConfigured = searchService.isConfigured;
  448. props.isSearchServiceReachable = searchService.isReachable;
  449. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  450. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  451. // props.isMailerSetup = mailService.isMailerSetup;
  452. props.isAclEnabled = aclService.isAclEnabled();
  453. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  454. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  455. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  456. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  457. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  458. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  459. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  460. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  461. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  462. props.editorConfig = {
  463. upload: {
  464. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  465. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  466. },
  467. };
  468. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  469. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  470. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  471. props.rendererConfig = {
  472. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  473. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  474. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  475. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  476. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  477. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  478. // XSS Options
  479. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  480. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  481. attrWhiteList: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  482. tagWhiteList: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  483. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  484. };
  485. }
  486. /**
  487. * for Server Side Translations
  488. * @param context
  489. * @param props
  490. * @param namespacesRequired
  491. */
  492. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  493. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  494. props._nextI18Next = nextI18NextConfig._nextI18Next;
  495. }
  496. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  497. const req = context.req as CrowiRequest<IUserHasId & any>;
  498. const { user } = req;
  499. const result = await getServerSideCommonProps(context);
  500. // check for presence
  501. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  502. if (!('props' in result)) {
  503. throw new Error('invalid getSSP result');
  504. }
  505. const props: Props = result.props as Props;
  506. if (props.redirectDestination != null) {
  507. return {
  508. redirect: {
  509. permanent: false,
  510. destination: props.redirectDestination,
  511. },
  512. };
  513. }
  514. if (user != null) {
  515. props.currentUser = user.toObject();
  516. }
  517. try {
  518. await injectPageData(context, props);
  519. }
  520. catch (err) {
  521. if (err instanceof MultiplePagesHitsError) {
  522. props.isIdenticalPathPage = true;
  523. }
  524. else {
  525. throw err;
  526. }
  527. }
  528. await injectRoutingInformation(context, props);
  529. injectServerConfigurations(context, props);
  530. await injectNextI18NextConfigurations(context, props, ['translation']);
  531. return {
  532. props,
  533. };
  534. };
  535. export default Page;